/*
 * support3
 */
package com.pitop.frontend.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baidu.fsg.uid.UidGenerator;
import com.pitop.core.base.BaseDAO;
import com.pitop.core.base.BaseSVImpl;
import com.pitop.core.entity.Page;
import com.pitop.core.exceptions.BaseException;
import com.pitop.core.exceptions.FrontendI18nException;
import com.pitop.core.tools.StringTools;
import com.pitop.frontend.dao.FrontendI18nCategoryDAO;
import com.pitop.frontend.dao.FrontendI18nDAO;
import com.pitop.frontend.entity.FrontendI18n;
import com.pitop.frontend.entity.FrontendI18nCategory;
import com.pitop.frontend.entity.FrontendI18nCategoryState;
import com.pitop.frontend.entity.FrontendI18nState;
import com.pitop.frontend.vo.LanguageTypeVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.map.HashedMap;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("frontendI18nSV")
@CacheConfig(cacheNames = "Support:FrontendI18n_Cache")
@Slf4j
public class FrontendI18nSVImpl extends BaseSVImpl<FrontendI18n, Long> implements FrontendI18nSV {

    @Autowired
    private FrontendI18nDAO frontendI18nDAO;

    @Autowired
    private FrontendI18nCategoryDAO frontendI18nCategoryDAO;

    @Resource
    private UidGenerator uidGenerator;

    @Override
    protected BaseDAO getBaseDAO() {
        return frontendI18nDAO;
    }

    /**
     * 保存前端国际化对象
     * 1.验证数据合法性
     * ****非空验证
     * ****分类编码正确性验证
     * ****查询插入或修改的数据是否为空
     * 2.遍历插入或修改数据
     *
     * @param entity 实体
     * @throws BaseException
     */
    @Override
    @CacheEvict(allEntries = true)
    public void save(FrontendI18n entity) throws BaseException {
        //1.数据合法性验证：非空验证
        if (entity == null) {
            throw new FrontendI18nException(BaseException.BaseExceptionEnum.Empty_Param);
        }
        if (StringTools.isEmpty(entity.getFronendCatetoryCode())) {
            throw new FrontendI18nException(BaseException.BaseExceptionEnum.Empty_Param);
        }
        if (StringTools.isEmpty(entity.getI18nKey())) {
            throw new FrontendI18nException(BaseException.BaseExceptionEnum.Empty_Param);
        }
      /*  if (StringTools.isEmpty(entity.getI18nValue())) {
            throw new FrontendI18nException(BaseException.BaseExceptionEnum.Empty_Param);
        }
        if (StringTools.isEmpty(entity.getLanguage())) {
            throw new FrontendI18nException(BaseException.BaseExceptionEnum.Empty_Param);
        }*/
        //分类编码是否正确
        FrontendI18nCategory frontendI18nCategory = frontendI18nCategoryDAO.loadByState(entity.getFronendCatetoryCode(), FrontendI18nCategoryState.Enable.name());
        if (frontendI18nCategory == null) {
            throw new FrontendI18nException(BaseException.BaseExceptionEnum.Result_Not_Exist);
        }
        //查询插入或修改的数据是否为空
        List<LanguageTypeVO> languageTypes = entity.getLanguageTypes();
        if (languageTypes == null || languageTypes.size() < 0) {
            throw new FrontendI18nException(BaseException.BaseExceptionEnum.Empty_Param);
        }
        //2.遍历插入或修改数据
        String i18nKey = entity.getI18nKey();
        String language;
        FrontendI18n frontendI18n;
        for (LanguageTypeVO languageType : languageTypes) {
            if (StringTools.isNotEmpty(languageType.getVal())) {
                language = languageType.getKey();
                frontendI18n = this.load(i18nKey, language);
                if (frontendI18n == null) {
                    //保存数据
                    entity.setCode(String.valueOf(uidGenerator.getUID()));
                    entity.setState(FrontendI18nState.Enable.name());
                    entity.setLanguage(language);
                    entity.setI18nValue(languageType.getVal());
                    super.save(entity);
                } else {
                    //修改数据
                    frontendI18n.setI18nValue(languageType.getVal());
                    this.update(frontendI18n);
                }
            }
        }
    }

    /**
     * 加载一个对象FrontendI18n
     *
     * @param id id* @param code 编码
     * @return FrontendI18n
     */
    @Override
    public FrontendI18n load(Long id, String code) {
        if (id == null && code == null) {
            throw new FrontendI18nException(BaseException.BaseExceptionEnum.Illegal_Param);
        }

        Map<String, Object> param = new HashMap<>();
        param.put("id", id);
        param.put("code", code);
        return frontendI18nDAO.load(param);
    }

    /**
     * 加载一个对象FrontendI18n 通过id
     *
     * @param id id
     * @return FrontendI18n
     */
    @Override
    public FrontendI18n loadById(Long id) {
        if (id == null) {
            throw new FrontendI18nException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        return frontendI18nDAO.loadById(id);
    }

    /**
     * 加载一个对象FrontendI18n 通过code
     *
     * @param code 编码
     * @return FrontendI18n
     */
    @Override
    public FrontendI18n loadByCode(String code) {
        if (code == null) {
            throw new FrontendI18nException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        return frontendI18nDAO.loadByCode(code);
    }

    /**
     * 查询某种语言下的所有国际化信息
     *
     * @param language 语言
     * @param state    状态
     * @return JSonObject
     */
    @Override
    @Cacheable(key = "#language.concat('-').concat('list')")
    public String watchByLanguage(String language, FrontendI18nState state) {
        if (StringTools.isEmpty(language)) {
            throw new FrontendI18nException(BaseException.BaseExceptionEnum.Empty_Param);
        }
        if (state == null) {
            throw new FrontendI18nException(BaseException.BaseExceptionEnum.Empty_Param);
        }
        language = language.replace("-", "_");
        List<FrontendI18n> frontendI18ns = frontendI18nDAO.listByLanguage(language, state.name());
        Map<String, Object> result = new HashedMap();
        for (FrontendI18n frontendI18n : frontendI18ns) {
            result.put(frontendI18n.getI18nKey(), frontendI18n.getI18nValue());
        }
        return StringTools.mapToJsonStr(result);
    }

    /**
     * 根据预约和国际化键查询前端国际化实体
     *
     * @param i18nKey  国际化键
     * @param language 语言
     * @return FrontendI18n
     */
    @Override
    public FrontendI18n load(String i18nKey, String language) {
        if (StringTools.isEmpty(i18nKey)) {
            throw new FrontendI18nException(BaseException.BaseExceptionEnum.Empty_Param);
        }
        if (StringTools.isEmpty(language)) {
            throw new FrontendI18nException(BaseException.BaseExceptionEnum.Empty_Param);
        }
        Map<String, Object> params = new HashedMap();
        params.put("i18nKey", i18nKey);
        params.put("language", language);
        return frontendI18nDAO.load(params);
    }


    /**
     * 根据主键id,oldStates 共同更新 FrontendI18n 的状态到newState状态
     *
     * @param id        id
     * @param newState  新状态
     * @param oldStates 旧状态集合
     */
    @Override
    @CacheEvict(allEntries = true)
    public void updateStateById(Long id, FrontendI18nState newState, FrontendI18nState... oldStates) {
        if (id == null) {
            throw new FrontendI18nException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        if (newState == null) {
            throw new FrontendI18nException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        if (oldStates == null) {
            throw new FrontendI18nException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        String[] states = new String[oldStates.length];
        for (int i = 0; i < oldStates.length; i++) {
            states[i] = oldStates[i].name();
        }
        frontendI18nDAO.updateStateById(id, new Date(), newState.name(), states);
    }

    /**
     * 根据主键code,oldStates 共同更新 FrontendI18n 的状态到newState状态
     *
     * @param code      编码
     * @param newState  新状态
     * @param oldStates 旧状态集合
     */
    @Override
    @CacheEvict(allEntries = true)
    public void updateStateByCode(String code, FrontendI18nState newState, FrontendI18nState... oldStates) {
        if (code == null) {
            throw new FrontendI18nException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        if (newState == null) {
            throw new FrontendI18nException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        if (oldStates == null) {
            throw new FrontendI18nException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        String[] states = new String[oldStates.length];
        for (int i = 0; i < oldStates.length; i++) {
            states[i] = oldStates[i].name();
        }
        frontendI18nDAO.updateStateByCode(code, new Date(), newState.name(), states);
    }

    /**
     * 根据主键id 更新 FrontendI18n 的状态到另一个状态
     *
     * @param id    id
     * @param state 状态
     */
    @Override
    @CacheEvict(allEntries = true)
    public void updateById(Long id, FrontendI18nState state) {
        if (id == null) {
            throw new FrontendI18nException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        frontendI18nDAO.updateById(id, state.name(), new Date());
    }

    /**
     * 根据主键code 更新 FrontendI18n 的状态到另一个状态
     *
     * @param code  编码
     * @param state 状态
     */
    @Override
    @CacheEvict(allEntries = true)
    public void updateByCode(String code, FrontendI18nState state) {
        if (code == null) {
            throw new FrontendI18nException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        frontendI18nDAO.updateByCode(code, state.name(), new Date());
    }

    /**
     * 修改前端国际化实体
     *
     * @param frontendI18n 实体
     */
    @Override
    @CacheEvict(allEntries = true)
    public void update(FrontendI18n frontendI18n) {
        super.modify(frontendI18n);
    }


    /**
     * 删除对象FrontendI18n
     *
     * @param id id* @param code 编码
     * @return FrontendI18n
     */
    @Override
    @CacheEvict(allEntries = true)
    public void delete(Long id, String code) {
        if (id == null && code == null) {
            throw new FrontendI18nException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        Map<String, Object> param = new HashMap<>();
        param.put("id", id);
        param.put("code", code);
        frontendI18nDAO.delete(param);
    }


    /**
     * 查询FrontendI18n分页
     *
     * @param frontendI18n 对象
     * @param offset       查询开始行
     * @param limit        查询行数
     * @return List<FrontendI18n>
     */
    @Override
    //@Cacheable(key = "list")
    public List<FrontendI18n> list(FrontendI18n frontendI18n, int offset, int limit) {
        if (offset < 0) {
            offset = 0;
        }

        if (limit < 0) {
            limit = Page.limit;
        }

        Map<String, Object> map = null;
        if (frontendI18n != null) {
            map = JSON.parseObject(JSON.toJSONString(frontendI18n, SerializerFeature.WriteDateUseDateFormat));
        } else {
            map = new HashMap<>();
        }
        return frontendI18nDAO.list(map, new RowBounds(offset, limit));
    }

    @Override
    public int count(FrontendI18n frontendI18n) {
        Map<String, Object> map = null;
        if (frontendI18n != null) {
            map = JSON.parseObject(JSON.toJSONString(frontendI18n, SerializerFeature.WriteDateUseDateFormat));
        } else {
            map = new HashMap<>();
        }
        return frontendI18nDAO.count(map);
    }

    /**
     * 查询FrontendI18n分页
     *
     * @param id     id* @param code  编码
     * @param offset 查询开始行
     * @param limit  查询行数
     * @return List<FrontendI18n>
     */
    @Override
    public List<FrontendI18n> list(Long id, String code, int offset, int limit) {
        if (offset < 0) {
            offset = 0;
        }

        if (limit < 0) {
            limit = Page.limit;
        }
        Map<String, Object> param = new HashMap<>();
        param.put("id", id);
        param.put("code", code);
        return frontendI18nDAO.list(param, new RowBounds(offset, limit));
    }

    @Override
    public int count(Long id, String code) {
        Map<String, Object> param = new HashMap<>();
        param.put("id", id);
        param.put("code", code);
        return frontendI18nDAO.count(param);
    }

    /**
     * 为FrontendI18n添加code
     *
     * @param frontendI18n
     */
    @Override
    public void updateToCreateCode(FrontendI18n frontendI18n) {
        if (frontendI18n == null) {
            return;
        }
        frontendI18n.setCode(String.valueOf(uidGenerator.getUID()));
        frontendI18nDAO.update(frontendI18n);
    }

    @Override
    public List<FrontendI18n> ListByI18nKey(String i18nKey, String language) {
        return   frontendI18nDAO.ListByI18nKey(i18nKey, language);
    }

}
